<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use DB;

class MealUserCard extends Model
{
    const CREATED_AT = 'insert_time';
    const UPDATED_AT = 'update_time';

    /**
     * 与模型关联的数据表。
     *
     * @var string
     */
    protected $table = 'lexiang_meal_user_card';

    protected $primaryKey = 'card_identi';

    public $timestamps = false;

    public function createCard($data)
    {
        $nowTime = time();
        $this->cards_id = $data['cards_id'];
        $this->users_id = $data['users_id'];
        $this->card_type = $data['card_type'];
        $this->card_num = $data['card_num'];
        $this->insert_time = $nowTime;
        $this->card_max_price = $data['card_max_price'];
        $this->order_id = $data['order_id'];
        $this->card_endtime = $data['card_endtime'];
        $this->card_invalid = 1;
        $this->card_already_num = 0;

        if($this->save()){
            return [
                'success'=>true,
                'code'=>'000',
                'message'=>'饭卡创建成功',
                'data'=>[
                    'buy_card_id'=>$this->card_identi,
                    'user_id'=>$data['users_id'],
                ]
            ];
        }else{
            return [
                'success'=>false,
                'code'=>'006',
                'message'=>'创建出错，请稍后再试'
            ];
        }
    }

    public static function userList($userid=false,$page=15)
    {
        return self::leftJoin('lexiang_meal_card','lexiang_meal_card.card_id','=','lexiang_meal_user_card.cards_id')
        ->where('lexiang_meal_user_card.users_id',$userid)
        ->select('lexiang_meal_user_card.card_identi','lexiang_meal_user_card.cards_id','lexiang_meal_user_card.card_invalid','lexiang_meal_user_card.insert_time','lexiang_meal_card.card_name','lexiang_meal_user_card.card_num')
        ->paginate($page,['userid','order-page'],'card-page');
    }

    /**
     * 增加当日使用次数
     */
    public function todayOnce($card_id)
    {
        $card = new MealUserCard;
        // MealUserCard::where('card_identi',$card_id)->select()->first();
    }

     /**
     * 使用
     */
    public function useCard(
        $cardId,
        $cateId,
        $userId,
        $shopId,
        $order_remarks='', // 备注
        $order_type=2,
        $help_user_id=0, // 帮带朋友ID
        $cate_num=1, // 订餐数量
        $payStatus=0,
        $maxprice=0,
        $carts=false,
        $payPrice=0
    ) {
        DB::beginTransaction();
        $userCard = $this->join('lexiang_meal_card','lexiang_meal_card.card_id','=','lexiang_meal_user_card.cards_id')
        ->where('lexiang_meal_user_card.card_identi',$cardId)
        ->select('lexiang_meal_user_card.*','lexiang_meal_card.card_frequency')
        ->first();
        if(!$userCard){
            return [
                'success'=>false,
                'resultCode'=>-1,
                'msg'=>"不存在的饭卡"
            ];
        }
        
        $nowTime = time();
        
        if($userCard->card_invalid == 0){
            return [
                'success'=>false,
                'resultCode'=>-1,
                'msg'=>"饭卡已经失效！"
            ];
        }

        if($userCard->card_num <= 0){
            return [
                'success'=>false,
                'resultCode'=>-1,
                'msg'=>"此饭卡次数已经用完了"
            ];
        }
        if($userCard->card_num < $cate_num){
            return [
                'success'=>false,
                'resultCode'=>-1,
                'msg'=>"饭卡次数不足{$cate_num}次，剩余{$userCard->card_num}次"
            ];
        }

        if($userCard->card_already_num == 0 && ($userCard->card_type == 0 || $userCard->card_type == 2)){
            $time30Day=strtotime(date('Y-m-d'))+($userCard->card_frequency*24*3600);
            $userCard->card_endtime = date('Y-m-d',$time30Day);
        }

        if(!empty($userCard->card_endtime)){
            if(strtotime($userCard->card_endtime.' 23:59:59') < $nowTime){
                return [
                    'success'=>false,
                    'resultCode'=>-1,
                    'msg'=>"该饭卡已于".$userCard->card_endtime."过期"
                ];
            }
        }
        $shop = new MealShop;
        $shopinfo_re = $shop->where('shop_id',$shopId)->first();
        $startDate = strtotime(date('Y-m-d '.$shopinfo_re->start_run_time));
        $overDate = strtotime(date('Y-m-d '.$shopinfo_re->over_run_time));
        $iftimebettwn = ($startDate <= $nowTime) && ($overDate >= $nowTime);
        if(!$iftimebettwn){
            return [
                'success'=>false,
                'resultCode'=>-1,
                'msg'=>"店铺不在营业时间内，去其他附近餐店看看吧"
            ];
        }

        if($shopinfo_re->shop_run_status != 1){
            return [
                'success'=>false,
                'resultCode'=>-1,
                'msg'=>"店铺今日休息，看看其他饭店吧"
            ];
        }

        $cardInfo = MealCard::where('card_id',$userCard->cards_id)->first();
        $cardStartTime = strtotime(date('Ymd ').$cardInfo->start_time);
        $cardEndTime = strtotime(date('Ymd ').$cardInfo->stop_time);
        // 使用时间
        $useTimeif = $cardStartTime < $nowTime && $cardEndTime > $nowTime;
        if(!$useTimeif){
            return [
                'success'=>false,
                'resultCode'=>-1,
                'msg'=>"饭卡不在可用时间内"
            ];
        }
        if(is_array($cateId)){
            $cateInfo = MealCate::whereIn('cate_id',$cateId)->where('cate_status',1)->get();
        }else{
            $cateInfo = MealCate::where('cate_id',$cateId)->first();
            if($cateInfo->cate_status == 0){
                return [
                    'success'=>false,
                    'resultCode'=>-1,
                    'msg'=>"该餐品已经下架，请选择其他餐品"
                ];
            }
            if($payStatus==0){
                if($cateInfo->cate_price > $cardInfo->meal_max_price){
                    return [
                        'success'=>false,
                        'resultCode'=>-1,
                        'msg'=>"饭卡不可购买大于".$cardInfo->meal_max_price.'元的餐品'
                    ];
                }
            }
        }
        
        $todaystart = strtotime(date('Ymd 00:00:00'));
        $todayend = strtotime(date('Ymd 23:59:59'));
        if($cardInfo->day_once < (MealOrder::where([
                    ['cards_id','=',$cardId],
                    ['users_id','=',$userId],
                    ['order_status','>',-1],
                ])->whereBetween('insert_time',[$todaystart,$todayend])->sum('cate_num')+$cate_num)){
            return [
                'success'=>false,
                'resultCode'=>-1,
                'msg'=>"今日饭卡次数已经用完了"
            ];
        }
        if($payStatus==0 || $payStatus == 3){
            $userCard->card_already_num = $userCard->card_already_num + $cate_num;
            $userCard->card_num = $userCard->card_num - $cate_num;
            if($userCard->card_num <= 0){
                $userCard->card_invalid = 0;
            }
            $userCard->update_time = $nowTime;
            $editUserCardRes = $userCard->save();

            if(!$editUserCardRes){
                DB::rollback();
                return [
                    'success'=>false,
                    'resultCode'=> -1,
                    'msg'=>"修改出错，请稍后再试！"
                ];
            }
        }
        

        $order = new MealOrder;

        $cateList = [];
        if($payStatus==0 || $payStatus==1){
            $cateInfo->cate_price = $cateInfo->cate_price+$maxprice;
            $cateInfo->select_num = $cate_num;
            $cateInfo->cate_sales = $cateInfo->cate_sales+$cate_num;
            if($cate_num > 1){
                $totalprice = round($cateInfo->cate_price * $cate_num,2);
            }else{
                $totalprice = $cateInfo->cate_price;
            }
            $carts = [];
            $carts[0] = $cateInfo->toArray();
        }else if($payStatus == 2 || $payStatus == 3){
            $totalprice = 0;
            $cnum = 0;
            foreach ($cateInfo as $key => $value) {
                $num = 1;
                foreach ($carts as $v) {
                    if($v['cate_id'] == $value->cate_id){
                        $num = $v['select_num'];
                    }
                }
                $cnum += $num;
                $value->cate_price = $num*$value->cate_price;
                $totalprice = $totalprice+$value->cate_price;
                $cateList[] = $value->cate_id;
            }
        }

        if($shopinfo_re->discount > 0){
            $totalprice = ($totalprice * $shopinfo_re->discount);
        }
        if($payStatus==0 || $payStatus == 3){
            // 更新锁防止并发篡改
            $shopinfo = User::where('user_id',$shopinfo_re->users_id)->lockForUpdate()->first();

            $shopinfo->account = round($shopinfo->account+$totalprice,2);
            
            $shopinfo->save();
        }
        if(is_array($cateId)){
            $cateId = $cateId[0];
        }
        $data = [
            'shops_id'=>$shopId,
            'users_id'=>$userId,
            'cates_id'=>$cateId,
            'cards_id'=>$cardId,
            'meal_order_price'=>$totalprice,
            'order_type'=>$order_type,
            'order_remarks'=>$order_remarks,
            'help_user_id'=>$help_user_id,
            'cate_num'=>$cate_num,
            'cate_list'=>implode(',',$cateList),
            'pay_price'=>$payPrice,
            'cart_cates'=>json_encode($carts)
        ];
        DB::commit();
        if($payStatus==1 || $payStatus == 2){
            return $order->postOrder($data,true);
        }else if($payStatus==0 || $payStatus == 3){
            return $order->postOrder($data);
        }
    }

    /**
     * 套餐
     */
    public function tccc($price){
        if($price <= 10){
            return 'card_num_198';
        }else if($price > 10 && $price <= 13){
            return 'card_num_258';
        }else if($price > 13 && $price <= 16){
            return 'card_num_298';
        }
    }

    public function getCardImgAttribute($v){
        return 'https://jiashilexiang.oss-cn-beijing.aliyuncs.com/MealCardImgs'.$v;
    }
}
